<template>
  <div class="box-card" v-loading="treeloading">
    <div slot="header" class="cardHeader tree-title-header">
      <span>问题预设分类</span>
      <el-button
        size="small"
        type="text"
        @click="handleAddClick"
        v-permission="['PROBLEM_PRESET_TYPE_ADD_BUTTON']"
      >新增</el-button>
    </div>
    <el-input
      v-model.trim="filterText"
      size="small"
      prefix-icon="el-icon-search"
      placeholder="请输入搜索项"
      maxlength="30"
      style="margin: 16px 0 0 0"
    />
    <div class="left-title" />
    <el-tree
      ref="tree"
      empty-text="暂无数据"
      :style="{ '--lightOpacity': lightTheme }"
      class="left-tree"
      :load="loadNode"
      lazy
      :props="defaultProps"
      :default-expand-all="false"
      :expand-on-click-node="false"
      :highlight-current="true"
      :current-node-key="currentKey"
      :filter-node-method="filterNode"
      node-key="id"
      :default-expanded-keys="expendData"
      @node-click="handleNodeClick"
      v-if="reload"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }" >
        <span>{{ node.label }}</span>
        <el-dropdown v-if="node.level > 1">
          <span @click.stop>
            <svg-icon class="el-dropdown-link" icon-class="sandian" />
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="empower(data, node)" v-permission="['PROBLEM_PRESET_TYPE_EMPOWER_BUTTON']">
              授权
            </el-dropdown-item>
            <el-dropdown-item @click.native="edit(data, node)" v-permission="['PROBLEM_PRESET_TYPE_EDIT_BUTTON']">
              修改
            </el-dropdown-item>
            <el-dropdown-item @click.native="remove(data, node)" v-permission="['PROBLEM_PRESET_TYPE_DEL_BUTTON']">
              删除
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </span>
    </el-tree>
    <dtDialog
      title="问题预设分类维护"
      :visible.sync="dialogVisible"
      :lock-scroll="false"
      :append-to-body="true"
      :is-loading="loading"
      @closeDialog="onModalClosed"
      @comfirmBtn="onSubmit"
    >
      <el-form
        ref="form"
        slot="content"
        label-width="130px"
        :model="form"
        :rules="rules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属系统" prop="systemId">
              <el-select v-model.trim="form.systemId" placeholder="请选择所属系统" style="width: 100%">
                <el-option
                  v-for="system in systemList"
                  :key="system.id"
                  :label="system.label"
                  :value="system.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!isAdd">
            <el-form-item label="分类编码" prop="classifyCode">
              <el-input v-model.trim="form.classifyCode" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类" prop="classifyName">
              <el-input
                v-model.trim="form.classifyName"
                maxlength="15"
                placeholder="请输入分类"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </dtDialog>
    <personSelect
      v-if="allocationShow"
      ref="personPicker"
      v-model="personValue"
      :params="params"
      :search-user-params="params"
      :api="bussinessRoleManageApi"
      :selectedData="[]"
      :tag-visible="false"
      :reappear="true"
      :selected-data="select"
      @handleSelectData="selected" />
  </div>
</template>

<script>
import {
  getSystemInfoList,
  getProblemType,
  addProblemClassify,
  editProblemClassify,
  delProblemClassify,
  countRoleAndProblem,
  getUserIdList,
  classifyEmpower
} from '@/api/problemPreset/index'
import { getRoleId } from '@/api/videoFusion/upstreamAccess'
import { getManagingOrgUserList, searchOrgName, searchUserName } from '@/framework/api/authCenter/bussinessRoleManage'
import { getUserListByUserIds } from '@/framework/api/affairManage/flowDetail/Config'

export default {
  components: {},
  data() {
    return {
      action: 1,
      filterText: '',
      tree: [
        {
          label: '小学招生平台',
          id: '123',
          children: [
            {
              label: '邯郸市丛台区曙光第六小学',
              id: '123-111'
            },
            {
              label: '邯郸市丛台区连城小学',
              id: '123-222'
            },
            {
              label: '丛台区弘文小学',
              id: '123-333'
            }
          ]
        },
        {
          label: '自然生态平台',
          id: '1234'
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: 'leaf'
      },
      currentKey: '',
      expendData: [],
      treeloading: false,
      loading: false,
      dialogVisible: false,
      form: {
        systemId: '',
        classifyName: '',
        classifyCode: ''
      },
      isAdd: true,
      rules: {
        systemId: [{ required: true, message: '请选择所属系统', trigger: ['blur', 'change'] }],
        classifyCode: [{ required: true, message: '请选择分类编码', trigger: ['blur', 'change'] }],
        classifyName: [{ required: true, message: '请输入分类', trigger: ['blur'] }]
      },
      allocationShow: false,
      params: {
        roleId: ''
      },
      personValue: '',
      bussinessRoleManageApi: { getManagingOrgUserList, searchOrgName, searchUserName, getUserListByUserIds },
      select: [],
      classifyId: '',
      systemList: [],
      newSystemId: '',
      reload: true,
      isFirst: true
    }
  },
  computed: {
    lightTheme() {
      return `${this.$store.state.settings.theme}19`
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    getRoleId().then((res) => {
      this.params.roleId = res.data
    })
  },
  methods: {
    async loadNode(node, reslove) {
      if (node.level == 0) {
        this.allNode = node
        this.allReslove = reslove
        try {
          this.treeloading = true
          const res = await getSystemInfoList()
          const treeArr = res.data.map((item) => {
            return {
              label: item.systemName,
              id: item.systemId,
              ...item
            }
          })
          this.expendData = treeArr.length ? [treeArr[0].id] : []
          this.treeloading = false
          this.systemList = treeArr
          return reslove(treeArr)
        } catch (error) {
          this.treeloading = false
        }
      }
      if (node.level > 0) {
        const res = await getProblemType(node.data.id)
        const treeArr = res.data.rows.map((item) => {
          return {
            label: item.classifyName,
            leaf: true,
            ...item
          }
        })
        if (this.isFirst) {
          this.currentKey = treeArr[0] && treeArr[0].id
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.currentKey)
            this.$emit('treeClick', treeArr[0])
          })
          this.isFirst = false
        }
        return reslove(treeArr)
      }
    },
    handleNodeClick(data, node) {
      if (node.level > 1) {
        this.$emit('treeClick', data)
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    empower(data, node) {
      this.allocationShow = false
      this.classifyId = data.id
      this.personValue = ''
      if (this.params.roleId) {
        setTimeout(() => {
          this.allocationShow = true
          getUserIdList(this.classifyId).then((res) => {
            this.personValue = res.data.join(',')
            setTimeout(() => {
              this.$refs.personPicker.show()
            }, 10)
          })
        }, 10)
      }
    },
    edit(data, node) {
      this.node = node
      this.isAdd = false
      this.dialogVisible = true
      this.form = { ...data }
    },
    remove(data, node) {
      countRoleAndProblem({ id: data.id, classifyCode: data.classifyCode }).then((res) => {
        let message
        if (res.data.problemNum > 0) {
          message = '该分类下存在问题预设，是否确认删除？'
        } else {
          message = '是否要删除？'
        }
        this.$dtModal.confirm(message).then(() => {
          delProblemClassify({ id: data.id, classifyCode: data.classifyCode }).then((res) => {
            this.$message.success(res.message)
            this.refreshParentTreeNode(node)
          })
        })
      })
    },
    handleAddClick() {
      this.isAdd = true
      this.dialogVisible = true
    },
    onModalClosed() {
      this.$refs.form.resetFields()
      this.form = {
        groupCode: '',
        groupName: ''
      }
    },
    onSubmit() {
      this.$refs.form.validate((result, message) => {
        if (result) {
          this.loading = true
          if (this.isAdd) {
            this.newSystemId = this.form.systemId
            addProblemClassify(this.form).then((res) => {
              this.$message.success(res.message)
              this.dialogVisible = false
              this.loading = false
              const node = this.$refs.tree.root.store.nodesMap[this.newSystemId]
              this.refreshTreeNode(node)
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.newSystemId = this.form.systemId
            editProblemClassify(this.form).then((res) => {
              this.$message.success(res.message)
              this.dialogVisible = false
              this.loading = false
              const node = this.$refs.tree.root.store.nodesMap[this.newSystemId]
              this.refreshTreeNode(node)
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    // 刷新父节点
    refreshParentTreeNode(node, isChangeSelect) {
      node.parent.loaded = false
      // 重新加载数据
      node.parent.loadData(() => {
        if (!isChangeSelect) { // 不改变选中项
          this.$refs.tree.setCurrentKey(this.currentKey || node?.data?.id || 0)
        } else { // 选中父节点
          this.currentNode = node.parent
          this.$refs.tree.setCurrentKey(node.parent?.data?.id || 0)
        }
      })
    },
    /* 刷新当前节点 */
    refreshTreeNode(node) {
      // 更改当前节点的加载状态
      node.loaded = false
      // 重新加载数据，入参为加载数据完成后执行的回调函数
      node.loadData(() => {
        // 设置选中节点（缺少此步骤则会丢失选中状态）
        this.$refs.tree.setCurrentKey(this.currentKey || 0)
      })
    },
    selected(select) {
      this.select = select
      const params = {
        classifyId: this.classifyId
      }
      params.userIds = this.select.map((item) => {
        return item.userId
      })
      // console.log(params)
      classifyEmpower(params).then((res) => {
        this.$dtModal.msgSuccess(res.message)
        this.classifyId = ''
        this.personValue = ''
        this.allocationShow = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.left-title {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-dropdown-link {
  margin-right: 8px;
  display: block;
  // width: 16px;
  // height: 16px;
  text-align: center;
  font-size: 14px;
}
.tree-title-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

